import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist  //  白名单   不需要有token的集合起来  可以直接跳转的不需要token

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start() //  开启进度条

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken() //  获取token

  if (hasToken) { //  判断token是否存在  token是否有值
    /*
    存在token
      - 放行  ？
      - 判断是不是 /login

    不存在token
      - 判断是不是 /login
        是login 放行
        不是login  跳回login
    */

    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      /*
         有token 判断是否有用户名
           有用户名   直接放行
           没有用户名 发送请求获取用户信息
         */
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          const { roles, userId } = await store.dispatch('user/getInfo')
          store.commit('user/SET_USERID', userId)
          console.log(roles, 666555)
          //  触发store中的permission中的设置routes函数
          const newRoutes = await store.dispatch('premission/froute', roles)

          router.addRoutes([...newRoutes, { path: '*', redirect: '/404', hidden: true }])
          console.log(router, 123222222)
          next(to.path)
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          // Message.error(error  || 'Has Error')
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
